package com.sms.web.system.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sms.common.Constants;
import com.sms.utils.TokenUtils;
import com.sms.web.rest.RestObject;
import com.sms.web.system.entity.SysUser;
import com.sms.web.system.service.SysUserService;
import com.sms.web.vo.SysUserVo;

/**
 * @desc 用户控制器
 * @author WuJiangWu
 * @date 2018年7月21日上午1:28:45
 */
@RestController
@RequestMapping(value= "/admin/user")
public class UserController {
    
    protected static Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private SysUserService userService;
    
    /**
     * 获取用户列表
     * @param id
     * @return
     */
    @GetMapping("/list")
    public RestObject getList(String queryLike, 
    		@RequestParam(defaultValue = "1") int pageNumber, 
    		@RequestParam(defaultValue = "20")int pageSize){
    	
    	RestObject rest = new RestObject();
    	Page<SysUser> page = userService.findByKeyword(queryLike, pageNumber, pageSize);
    	rest.setState(0);
    	rest.setData(page);
    	return rest;
    }
    
    /**
     * 获取当登录用户信息
     * @param id
     * @return
     */
    @GetMapping("/info")
    public RestObject info(HttpServletRequest request) {
    	RestObject rest = new RestObject(); 
    	SysUser user = (SysUser) request.getSession().getAttribute(Constants.USER_SESSION_NAME);
         if(user != null){
        	 rest.setData(user);
             return rest;
         }
         String token = request.getHeader(Constants.TOKEN_COOKIE_NAME);
         if( StringUtils.isNotBlank(token) ) {
         	user =TokenUtils.getUser(token);
             if(user != null){
                 request.getSession().setAttribute(Constants.USER_SESSION_NAME,user);
                 rest.setData(user);
                 return rest;
             }
         }
         //session过期且token过期或未登录
         return RestObject.newRestObject(RestObject.STATUS_CODE_NOT_LOGIN, "未登陆或登陆已过期");
    }
    
    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public RestObject getUser(@PathVariable() String id) {
    	
    	RestObject rest = new RestObject();
    	SysUser user = userService.findUser(id);
    	rest.setState(0);
    	rest.setData(user);
    	return rest;
    }
    
    /**
     * 添加/更新用户信息
     * @param user
     * @return
     */
    @PutMapping("/")
    public RestObject saveUser(SysUserVo vo){
    	try {
            if (StringUtils.isEmpty(vo.getId())) {
                // 是否存在相同的用户
                SysUser u = userService.findByUsername(vo.getUsername());
                if (u != null) {
                    return RestObject.newError("已经存在相同账号的用户");
                }
            }
            SysUser newUser = userService.saveUser(vo);
            return RestObject.newOk(newUser);
        } catch (Exception e) {
            logger.error("保存用户信息时异常", e);
            return RestObject.newError(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public RestObject deleteUser(@PathVariable()String id){
    	try {
            userService.deleteUser(id);
            return RestObject.newOk("success");
        } catch (Exception ex) {
            logger.error("删除用户时异常", ex);
            return RestObject.newError(ex.getMessage());
        }
    }

    /**
     * 更新密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @PutMapping(value = "/{id}/savepassword")
    public RestObject savePassword(@PathVariable()String id, 
    		@RequestParam("oldPassword") String oldPassword, 
    		@RequestParam("newPassword") String newPassword) {
    	
    	try {
            SysUser user = userService.findCurrentUser();
            if (user == null) {
                return RestObject.newError("当前用户不存在");
            } else if (oldPassword.equals(user.getPassword())) {
                return RestObject.newError("旧密码不正确");
            }
            userService.updatePasswordById(newPassword, user.getId());
            return RestObject.newOk("success");
        } catch (Exception ex) {
            logger.error("更新用户密码异常", ex);
            return RestObject.newError(ex.getMessage());
        }
    }
    
}
